﻿namespace StreetCrime
{
    using System;
    using System.Diagnostics;
    using System.Reactive.Linq;
    using System.Reflection;
    using Models;
    using Services;
    using WP7Contrib.Caching;
    using WP7Contrib.Communications;

    using System.Collections.Generic;
    using System.Windows;
    using Microsoft.Phone.Controls;
    using WP7Contrib.Logging;
    using WP7Contrib.Services.Location;

    public partial class MainPage : PhoneApplicationPage
    {
        private readonly IsolatedStorageCacheProvider cacheProvider;
        private readonly string username;
        private readonly string password;
        private readonly string url;

        private readonly IHandleResources resourceClient;
        private ISearchStreetLevelCrime crimeService;
        private double @lat;
        private double @long;
        private LocationService locationService;
        private DebugLog log;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            var assemblies = new List<Assembly> {this.GetType().Assembly};
            cacheProvider = new IsolatedStorageCacheProvider("StreetCrime", assemblies, new NullLoggingService());

            log = new DebugLog();
            
            username = "your username";
            password = "your password";

            url = "http://policeapi2.rkh.co.uk/api/crimes-street/all-crime?lat={0}&lng={1}";

            @lat = 52.629729;
            @long = -1.131592;

            resourceClient = new ResourceClient(log);
            crimeService = new StreetLevelCrimeService(resourceClient,
                                                      cacheProvider,
                                                      log,
                                                      url,
                                                      username,
                                                      password);

            locationService = new LocationService(log);
        }

        private void HandleRuralClick(object sender, RoutedEventArgs e)
        {
            var criteria = new StreetLevelCrimeCriteria { Latitude = 53.138738944029086, Longitude = -3.24371337890625 };
            GetCrimeStatsImpl(criteria, "RURAL");
        }

        private void HandleUrbanClick(object sender, RoutedEventArgs e)
        {
            var criteria = new StreetLevelCrimeCriteria { Latitude = 51.549564212835215, Longitude = -0.05945920944213867 };
            GetCrimeStatsImpl(criteria, "URBAN");
        }

        private void GetCrimeStatsImpl(StreetLevelCrimeCriteria criteria, string area)
        {
            log.Write("Searching for crimes started - " + area);

            var sw = new Stopwatch();
            sw.Start();
            crimeService.Search(criteria)
                .ObserveOnDispatcher()
                .Subscribe(result =>
                {
                    log.Write("Crimes found...");
                    log.Write("Crime count = {0}", result.Crimes.Count);

                    response.Text = "Successfully returned crime stats...";
                    crimeCount.Text = string.Format("Crime count = {0}", result.Crimes.Count);
                },
                exception =>
                {
                    response.Text = "Failed returned crime stats...";
                    crimeCount.Text = "";
                },
                () =>
                {
                    sw.Stop();
                    log.Write("Elapsed time = {0} ms", sw.ElapsedMilliseconds);
                    log.Write("Searching for crimes completed...");
                    elapsedTime.Text = string.Format("Elapsed time = {0} ms", sw.ElapsedMilliseconds);
                });

        }
    }
}